﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VergenereEncryptionWinForm
{
    /// <summary>
    /// 加密类
    /// </summary>
    internal class Encryption
    {   /// <summary>
        /// 明文
        /// </summary>
        public string Plain { get; set; }
        /// <summary>
        /// 总密钥
        /// </summary>
        public string Key { get; set; }
        /// <summary>
        /// 小写字母密钥
        /// </summary>
        public string Key1 { get; set; }
        /// <summary>
        ///大写字母密钥
        /// </summary>
        public string Key2 { get; set; }
        /// <summary>
        /// 密文
        /// </summary>
        public string CipherText { get; set; }
        /// <summary>
        /// 加密过程
        /// </summary>
        public void Encode()
        {
            for (int i = 0; i < Plain.Length; i++)
            {
                int ASCII;
                //小写字母加密
                if (Plain[i] >= 'a')
                //明文与密钥匹配后转换为ASCII码
                {
                    ASCII = 'a' + CharToASCII1(Key1[i % Key1.Length]) + CharToASCII1(Plain[i]);
                    //将超范围的ASCII码转换为正确值
                    if (ASCII > 122)
                    {
                        ASCII -= 26;
                    }
                    //ASCII码进去加密后的字符串
                    CipherText += Convert.ToChar(ASCII);
                }
                //大写字母加密
                //明文与密钥匹配后转换为ASCII码
                else
                {
                    ASCII = 'A' + CharToASCII2(Key2[i % Key2.Length]) + CharToASCII2(Plain[i]);
                    //将超范围的ASCII码转换为正确值
                    if (ASCII > 90)
                    {
                        ASCII -= 26;
                    }
                    //ASCII码转成加密后的字符串
                    CipherText += Convert.ToChar(ASCII);
                }
            }

        }
        /// <summary>
        /// 将字符转换为ASCII码  小写转换
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private int CharToASCII1(char ch)
        {
            return ch - 'a';
        }
        /// <summary>
        /// 大写转换
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private int CharToASCII2(char ch)
        {
            return ch - 'A';
        }
    }
}
